import { checkLoginStatus, showMessage } from './common.js';
import api from './api.js';

// 初始化首页
async function initHomePage() {
    try {
        // 检查登录状态
        const user = await checkLoginStatus();

        // 加载商品数据
        await loadProducts();

        // 初始化事件监听
        initEventListeners();

        console.log('首页初始化完成');
    } catch (error) {
        console.error('首页初始化失败:', error);
        showMessage('error', '页面加载失败，请刷新重试');
    }
}

// 加载商品数据
async function loadProducts() {
    try {
        const response = await api.products.getByPage(1, 8);
        if (response && response.data) {
            renderProducts(response.data);
        }
    } catch (error) {
        console.error('加载商品失败:', error);
        showMessage('error', '加载商品失败');
    }
}

// 渲染商品列表
function renderProducts(products) {
    const productGrid = document.querySelector('.product-grid');
    if (!productGrid) return;

    productGrid.innerHTML = products.map(product => `
        <div class="product-card" data-id="${product.id}">
            <div class="product-image">
                <img src="${product.imageUrl || 'https://picsum.photos/300/200'}" alt="${product.name}">
            </div>
            <div class="product-info">
                <h3>${product.name}</h3>
                <div class="price">¥${product.price.toFixed(2)}</div>
                <div class="meta">
                    <span><i class="fas fa-map-marker-alt"></i> ${product.location || '未知地点'}</span>
                    <span><i class="fas fa-clock"></i> ${formatTime(product.createdAt)}</span>
                </div>
            </div>
        </div>
    `).join('');
}

// 格式化时间
function formatTime(timestamp) {
    if (!timestamp) return '未知时间';
    const date = new Date(timestamp);
    return date.toLocaleDateString();
}

// 初始化事件监听
function initEventListeners() {
    // 商品点击事件
    document.addEventListener('click', (e) => {
        const productCard = e.target.closest('.product-card');
        if (productCard) {
            const productId = productCard.dataset.id;
            window.location.href = `product-detail.html?id=${productId}`;
        }
    });

    // 搜索功能
    const searchBox = document.querySelector('.search-box');
    if (searchBox) {
        searchBox.addEventListener('submit', (e) => {
            e.preventDefault();
            const keyword = searchBox.querySelector('input').value.trim();
            if (keyword) {
                window.location.href = `products.html?search=${encodeURIComponent(keyword)}`;
            }
        });
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initHomePage);